package com.itheima.web.servlet;


import com.alibaba.fastjson.JSON;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet{


    private UserService userService=new UserServiceImpl();

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接受表单数据
        BufferedReader br=request.getReader();
        //2.读取一行json字符串
        String params=br.readLine();
        //3.json将字符串转为user对象
        User user = JSON.parseObject(params, User.class);
        //4.判断用户身份,调用对应方法，相应对应标识
        if(user.getFlag().equals("管理员")){
            userService.addManager(user);
            response.getWriter().write("managerSuccess");
        }else if(user.getFlag().equals("普通用户")){
            userService.addNormalUser(user);
            response.getWriter().write("normalUserSuccess");
        }

    }
    public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接受表单数据
        BufferedReader br=request.getReader();
        //2.读取一行json字符串
        String params=br.readLine();
        //3.json将字符串转为user对象
        User user = JSON.parseObject(params, User.class);
        //4.判断用户身份,调用对应方法，相应对应标识
        boolean flag=false;
        if(user.getFlag().equals("管理员")){
            User user1=userService.selectManager(user);
           if(user1!=null)
               response.getWriter().write("managerSuccess");
           else
               response.getWriter().write("fail");
        } else if (user.getFlag().equals("普通用户")) {
            User user2=userService.selectNormalUser(user);
            if(user2!=null)
                response.getWriter().write("normalUserSuccess");
            else
                response.getWriter().write("fail");
        }

    }
}
